package mqtt

import (
	pmqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

const (
	defaultClientCycleDuration = 10 * time.Minute //默认客户端定时清理周期时长
	defaultClientTtl           = 30 * time.Minute //默认客户端存活时长
	defaultMaxReplyTime        = 5 * time.Second  //默认最大回复时长
	defaultReplyCycleDuration  = 1 * time.Second  //默认回复定时清理周期时长
	defaultReplyTtl            = 10 * time.Second //默认回复存活时长
)

type (
	SubscribeHandler func(s *Server) pmqtt.MessageHandler
	Subscribe        struct {
		Topic   string
		Qos     byte
		Handler SubscribeHandler
	}
)

type Conf struct {
	ClientID    string
	Password    string
	UserName    string `json:"userName,omitempty"`
	Dns         string `json:"dns,default=tcp://127.0.0.1:1883"`
	KeepAlive   int    `json:"keepAlive,default=60"`
	PingTimeout int    `json:"pingTimeout,default=1"`
}

func newMqtt(conf Conf) (c pmqtt.Client, e error) {
	opts := pmqtt.NewClientOptions()

	opts.AddBroker(conf.Dns)
	opts.SetClientID(conf.ClientID)
	opts.SetKeepAlive(time.Second * time.Duration(conf.KeepAlive))
	opts.SetPingTimeout(time.Second * time.Duration(conf.PingTimeout))

	if conf.UserName != "" {
		opts.SetUsername(conf.UserName)
	}
	if conf.Password != "" {
		opts.SetPassword(conf.Password)
	}
	c = pmqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		e = token.Error()
		return
	}
	return
}
